package com.mfw.springboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mfw.springboot.annotation.AuthCheck;
import com.mfw.springboot.common.BaseResponse;
import com.mfw.springboot.common.DataGroupByDateDTO;
import com.mfw.springboot.common.DeleteRequest;
import com.mfw.springboot.common.ErrorCode;
import com.mfw.springboot.common.Result;
import com.mfw.springboot.constant.UserConstant;
import com.mfw.springboot.exception.BusinessException;
import com.mfw.springboot.exception.ThrowUtils;
import com.mfw.springboot.model.dto.evaluation.EvaluationAddRequest;
import com.mfw.springboot.model.dto.evaluation.EvaluationEditRequest;
import com.mfw.springboot.model.dto.evaluation.EvaluationQueryRequest;
import com.mfw.springboot.model.dto.evaluation.EvaluationUpdateRequest;
import com.mfw.springboot.model.entity.Evaluation;
import com.mfw.springboot.model.entity.User;
import com.mfw.springboot.model.vo.EvaluationVO;
import com.mfw.springboot.service.EvaluationService;
import com.mfw.springboot.service.UserService;
import com.mfw.springboot.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 评价接口
 *
 * @author mfw
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@RestController
@RequestMapping("/evaluation")
@Slf4j
public class EvaluationController {

    @Resource
    private EvaluationService evaluationService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建评价
     *
     * @param evaluationAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addEvaluation(@RequestBody EvaluationAddRequest evaluationAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(evaluationAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        Evaluation evaluation = new Evaluation();
        BeanUtils.copyProperties(evaluationAddRequest, evaluation);
        // 数据校验
        evaluationService.validEvaluation(evaluation, true);
        // 写入数据库
        boolean result = evaluationService.save(evaluation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newEvaluationId = evaluation.getId();
        return Result.success(newEvaluationId);
    }

    /**
     * 删除评价
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteEvaluation(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Evaluation oldEvaluation = evaluationService.getById(id);
        ThrowUtils.throwIf(oldEvaluation == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅管理员可删除
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = evaluationService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 更新评价（仅管理员可用）
     *
     * @param evaluationUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateEvaluation(@RequestBody EvaluationUpdateRequest evaluationUpdateRequest) {
        if (evaluationUpdateRequest == null || evaluationUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        Evaluation evaluation = new Evaluation();
        BeanUtils.copyProperties(evaluationUpdateRequest, evaluation);
        // 数据校验
        evaluationService.validEvaluation(evaluation, false);
        // 判断是否存在
        long id = evaluationUpdateRequest.getId();
        Evaluation oldEvaluation = evaluationService.getById(id);
        ThrowUtils.throwIf(oldEvaluation == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = evaluationService.updateById(evaluation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 根据 id 获取评价（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<EvaluationVO> getEvaluationVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Evaluation evaluation = evaluationService.getById(id);
        ThrowUtils.throwIf(evaluation == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return Result.success(evaluationService.getEvaluationVO(evaluation, request));
    }

    /**
     * 分页获取评价列表（仅管理员可用）
     *
     * @param evaluationQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Evaluation>> listEvaluationByPage(@RequestBody EvaluationQueryRequest evaluationQueryRequest) {
        long current = evaluationQueryRequest.getCurrent();
        long size = evaluationQueryRequest.getPageSize();
        // 查询数据库
        Page<Evaluation> evaluationPage = evaluationService.page(new Page<>(current, size),
                evaluationService.getQueryWrapper(evaluationQueryRequest));
        return Result.success(evaluationPage);
    }

    /**
     * 分页获取评价列表（封装类）
     *
     * @param evaluationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<EvaluationVO>> listEvaluationVOByPage(@RequestBody EvaluationQueryRequest evaluationQueryRequest,
                                                               HttpServletRequest request) {
        long current = evaluationQueryRequest.getCurrent();
        long size = evaluationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Evaluation> evaluationPage = evaluationService.page(new Page<>(current, size),
                evaluationService.getQueryWrapper(evaluationQueryRequest));
        // 获取封装类
        return Result.success(evaluationService.getEvaluationVOPage(evaluationPage, request));
    }

    /**
     * 分页获取当前登录用户创建的评价列表
     *
     * @param evaluationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<EvaluationVO>> listMyEvaluationVOByPage(@RequestBody EvaluationQueryRequest evaluationQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(evaluationQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        String role = loginUser.getRole();
        if (UserConstant.DEFAULT_ROLE.equals(role)){
            evaluationQueryRequest.setStudentId(loginUser.getId());
        } else if (UserConstant.COACH_ROLE.equals(role)) {
            evaluationQueryRequest.setCoachId(loginUser.getId());
        }

        long current = evaluationQueryRequest.getCurrent();
        long size = evaluationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Evaluation> evaluationPage = evaluationService.page(new Page<>(current, size),
                evaluationService.getQueryWrapper(evaluationQueryRequest));
        // 获取封装类
        return Result.success(evaluationService.getEvaluationVOPage(evaluationPage, request));
    }

    /**
     * 编辑评价（给用户使用）
     *
     * @param evaluationEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editEvaluation(@RequestBody EvaluationEditRequest evaluationEditRequest, HttpServletRequest request) {
        if (evaluationEditRequest == null || evaluationEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        Evaluation evaluation = new Evaluation();
        BeanUtils.copyProperties(evaluationEditRequest, evaluation);
        // 数据校验
        evaluationService.validEvaluation(evaluation, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = evaluationEditRequest.getId();
        Evaluation oldEvaluation = evaluationService.getById(id);
        ThrowUtils.throwIf(oldEvaluation == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅管理员可编辑
        if (!userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = evaluationService.updateById(evaluation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
    * 日新增统计评价
    *
    * @return
    */
    @PostMapping("/day/newly/added")
    public BaseResponse<List<DataGroupByDateDTO>> dayNewlyAddedEvaluation() {
        // 今天
        Date endDate = DateUtils.getNow();
        // 30天以前
        Date beginDate = DateUtils.dayAfter(endDate, -30);
        // 查询
        List<DataGroupByDateDTO> evaluationDataList = evaluationService.countByDay(beginDate, endDate);
        //返回结果
        return Result.success(evaluationDataList);

    }

    // endregion
}
